package org.apache.skywalking.apm.plugin.kepler;

import com.xiaomaoguai.fcp.pre.kepler.common.utils.JsonUtils;
import com.xiaomaoguai.fcp.pre.kepler.router.handler.handlercontext.DefaultHandlerContext;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.StringTag;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;

import java.lang.reflect.Method;

/**
 * @author WeiHui-Z
 * @version v1.0.0
 * @date 2019/5/17 20:48
 * @since JDK 1.8
 */
public class KeplerHandlerInterceptor implements InstanceMethodsAroundInterceptor {

	@Override
	public void beforeMethod(EnhancedInstance enhancedInstance, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult methodInterceptResult) throws Throwable {
		final DefaultHandlerContext handlerContext = (DefaultHandlerContext) allArguments[0];
		final Object innerParam = handlerContext.getInnerParam();
		AbstractSpan activeSpan = ContextManager.activeSpan();
		activeSpan.tag(new StringTag("convertDTO"), JsonUtils.toFormatJsonString(innerParam));
	}

	@Override
	public Object afterMethod(EnhancedInstance enhancedInstance, Method method, Object[] allArguments, Class<?>[] argumentsTypes, Object o) throws Throwable {
		return o;
	}

	@Override
	public void handleMethodException(EnhancedInstance enhancedInstance, Method method, Object[] allArguments, Class<?>[] argumentsTypes, Throwable throwable) {
		ContextManager.activeSpan().errorOccurred().log(throwable);
	}

}
